<template>
  <div class="bomBuyer">
    <ele-form-search
      ref="eleFormSearch"
      :formConfig="searchConfig"
      :openDown="true"
      @handleSearch="handleSearch"
      @handleReset="handleReset"
    ></ele-form-search>
    <div class="content-main">
      <div class="left-table">
        <ele-table
          ref="domTable"
          :column="domColumn"
          :getList="getRequirementList"
          :beforeRequest="selfMasterBeforeRequest"
          :operateList="masterOperateList"
          @handleOperateEvent="handleMasterOperateEvent"
          @row-click="masterRowClick"
        >
        </ele-table>
      </div>
      <div class="right-table">
        <div class="detail-info-main" v-if="materialCountData">
          <div class="title-p">
            物料状态数据统计
          </div>
          <div class="info-main">
            <!-- <div class="info-item">
              <span class="info-label">物料需求数量:</span>
              <span class="info-text">
              {{ masterDetail.materialTypeNum }}
              </span>
            </div> -->
            <div class="info-item" v-for="item in materialCountData.result" :key="`count-${item.status}`">
              <span class="info-label">{{ item.demandStatus }}:</span>
              <span class="info-text">
                {{ item.num }}
              </span>
            </div>
            <!-- <div class="info-item">
              <span class="info-label">{{ $i18n.t("bomBuyer.bomCode") }}：</span>
              <span class="info-text">
                {{ masterDetail.recheckOrderCode||'-' }}
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">{{ $i18n.t("bomBuyer.bomVin") }}：</span>
              <span class="info-text">
                {{ masterDetail.vinCode||'-' }}
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">{{ $i18n.t("bomBuyer.createTime") }}：</span>
              <span class="info-text">
                {{ masterDetail.createTime||'-' }}
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">{{ $i18n.t("bomBuyer.carType") }}：</span>
              <span class="info-text">
                {{ masterDetail.modelName||'-' }}
              </span>
            </div> -->
          </div>
        </div>
        <div class="sub-table-table">
          物料需求列表
        </div>
        <div class="sub-form-search">
          <ele-form-search
            ref="eleDetailFormSearch"
            :formConfig="detailSearchConfig"
            @handleSearch="handleDetailSearch"
            @handleReset="handleDetailReset"
          ></ele-form-search>
        </div>
        <ele-table
          ref="domDetailTable"
          :column="detailColumn"
          :apiImmediate="false"
          :getList="mesPcMaterialDemandGetList"
          :beforeRequest="selfSubBeforeRequest"
          :operateList="operateList"
          @handleOperateEvent="handleOperateEvent"
        >
        </ele-table>
      </div>
    </div>
    <detail-drawer ref="detailDrawerRef" @updateList="updateDomDetailTable" />
    <el-image-viewer
      v-if="showViewer"
      :on-close="closeViewer"
      :url-list="showViewerImages"
      :initialIndex="initialIndex"
    />
  </div>
</template>

<script>
import eleFormSearch from '@/components/ele-form-search/index'
import { exportExcel } from "@/utils/judge";
import { operateList, searchConfig, detailSearchConfig, rowConfig } from './config'
import { getRequirementList, mesPcMaterialDemandGetList, reinquiryRequest, exportUrl, exportAllUrl, getMaterialCount } from '@/api/materials/bomBuyer.js'
import { searchArrKey } from '@/mixins/searchArrKey'
import detailDrawer from './detailDrawer.vue'

import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
// import url from '@/axios/url'
// import { exportExcel } from '@/utils/judge'
// const { minioUrl } = url()
export default {
  name: 'supplier',
  components: {
    eleFormSearch,
    detailDrawer,
    ElImageViewer
  },
  mixins: [searchConfig, detailSearchConfig, operateList, searchArrKey],
  data() {
    let _self = this
    return {
      formConfig: {},
      processCodeList: [],
      isLoading: false,
      loading: false,
      formDataDialog: {},
      masterSearchData: { material: 1 },
      getRequirementList,
      mesPcMaterialDemandGetList,
      // 列表页字段的绑定配置
      domColumn: [
        {
          type: 'index',
          label: $i18n.t('common.order'),
          width: 60,
          fixed: 'left'
        },
        {
          prop: 'recheckOrderCode',
          label: $i18n.t('bomBuyer.bomCode'),
          minWidth: 150,
          showOverflowTooltip: true,
          noChecked: true
        },
        {
          prop: 'vinCode',
          label: $i18n.t('bomBuyer.bomVin'),
          minWidth: 170,
          showOverflowTooltip: true
        },
        {
          prop: 'modelName',
          label: $i18n.t('bomBuyer.carType'),
          minWidth: 170,
          showOverflowTooltip: true
        },
        {
          prop: 'materialTypeNum',
          label: $i18n.t('bomBuyer.materialTypeNum'),
          minWidth: 150,
          showOverflowTooltip: true
        },
        {
          prop: 'confirmTypeNum',
          label: $i18n.t('bomBuyer.confirmedMaterialTypeNum'),
          minWidth: 180,
          showOverflowTooltip: true,
          render: (h, scope) => {
            return <span class="blue-num">{scope.row.confirmTypeNum}</span>
          }
        },
        {
          prop: 'inquiredNum',
          label: '待选择物料类型数量',
          minWidth: 150,
          showOverflowTooltip: true,
          render: (h, scope) => {
            return <span class="blue-num">{scope.row.inquiredNum}</span>
          }
        },
        {
          prop: 'inquiryNum',
          label: '询价中物料类型数量',
          minWidth: 150,
          showOverflowTooltip: true,
          render: (h, scope) => {
            return <span class="blue-num">{scope.row.inquiryNum}</span>
          }
        },
        {
          prop: 'arriveNum',
          label: '已到货物料类型数量',
          minWidth: 150,
          showOverflowTooltip: true,
          render: (h, scope) => {
            return <span class="blue-num">{scope.row.arriveNum}</span>
          }
        },
        {
          prop: 'createTime',
          label: $i18n.t('bomBuyer.createTime'),
          minWidth: 160,
          showOverflowTooltip: true,
          noChecked: true
        }
      ],
      rowParams: {
        recheckOrderId: null
      }, //主表点击后子表
      masterDetail: {
        materialNum: 0,
        recheckOrderCode: null,
        vinCode: null,
        modelName: null,
        createTime: null
      },
      materialCountData: null,
      detailColumn: [
        {
          type: 'index',
          label: $i18n.t('common.order'),
          width: 60,
          fixed: 'left'
        },
        {
          prop: 'materialName',
          label: $i18n.t('bomBuyer.materialName'),
          minWidth: 140,
          showOverflowTooltip: true
        },
        {
          prop: 'demandStatus',
          label: $i18n.t('common.status'),
          minWidth: 140,
          showOverflowTooltip: true,
          render: (h, scope) => {
            return (
              <span>
                <span class={`${_self.getClassName(scope.row.demandStatus)} status-circle`}></span>
                <span>{scope.row.demandStatus}</span>
              </span>
            )
          }
        },
        {
          prop: 'quoNum',
          label: $i18n.t('bomBuyer.goodsQuotedNum'),
          minWidth: 140,
          showOverflowTooltip: true,
          renderHeader: (h, scope) => {
            return (
              <span>
                <span>{$i18n.t('bomBuyer.goodsQuotedNum')}</span>
                <el-tooltip class="item" effect="dark" content={$i18n.t('bomBuyer.prompt1')} placement="top-start">
                  <i class="el-icon-info warning-icon"></i>
                </el-tooltip>
              </span>
            )
          }
        },
        {
          prop: 'materialNum',
          label: $i18n.t('bomBuyer.quantity'),
          minWidth: 140,
          showOverflowTooltip: true
        },
        {
          prop: 'unit',
          label: $i18n.t('bomBuyer.unit'),
          minWidth: 140,
          showOverflowTooltip: true,
          render: (h, scope) => {
            return <span>个/L</span>
          }
        },
        {
          prop: 'materialPhotoUrl',
          label: $i18n.t('bomBuyer.picture'),
          minWidth: 140,
          showOverflowTooltip: true,
          render: (h, scope) => {
            let _dom = []
            if (scope.row.materialPhotoUrl) {
              _dom.push(
                <el-link
                  type="primary"
                  onClick={() => {
                    this.showImgViewer(scope.row)
                  }}
                >
                  {$i18n.t('common.view')}
                </el-link>
              )
            } else {
              _dom.push(<span>-</span>)
            }
            return _dom
          }
        },
        {
          prop: 'createByName',
          label: $i18n.t('bomBuyer.creator'),
          minWidth: 140,
          showOverflowTooltip: true
        },
        {
          prop: 'createTime',
          label: $i18n.t('bomBuyer.createTime'),
          minWidth: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'deadlineTime',
          label: $i18n.t('bomBuyer.offerDeadline'),
          minWidth: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'operate',
          label: $i18n.t('common.operation'),
          width: 200,
          fixed: 'right',
          render: (h, scope) => {
            return <ele-row-operation scope={scope} rowConfig={rowConfig} onRowOperate={this.rowOperate} />
          }
        }
      ],
      showViewer: false,
      initialIndex: 0,
      showViewerImages: [
        'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg',
        'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg'
      ]
    }
  },
  computed: {},
  methods: {
    //主表搜索
    handleSearch() {
      this.refresh()
      this.subResetData()
    },
    //主表重置
    handleReset() {
      this.refresh()
      this.subResetData()
    },
    //子表搜索
    handleDetailSearch() {
      this.subRefresh()
    },
    //子表重置
    handleDetailReset() {
      this.subRefresh()
    },
    // 主表，请求之前操作
    selfMasterBeforeRequest(data) {
      const params = { ...data, ...this.masterSearchData, ...this.getSearchParams() }
      if (Array.isArray(params.dateRanger)) {
        params.startTime = params.dateRanger[0]
        params.endTime = params.dateRanger[1]
        delete params.dateRanger
      }
      return params
    },
    // 子表，请求之前操作
    selfSubBeforeRequest(data) {
      const params = { ...data, ...this.rowParams, ...this.getDetailSearchParams() }
      return params
    },
    // 获取搜索参数
    getSearchParams() {
      let formData = this.$refs.eleFormSearch.formData || {}
      formData = this.getArrtoMap(formData)
      return formData
    },
    // 获取搜索参数
    getDetailSearchParams() {
      let formData = this.$refs.eleDetailFormSearch.formData || {}
      formData = this.getArrtoMap(formData)
      return formData
    },
    // 点击主表行
    masterRowClick(row) {
      this.getSubRequestParams(row)
      this.$refs.domDetailTable.getTableData(true)
      getMaterialCount({id: row.id}).then(res => {
        if (res.data.success) {
          this.materialCountData = res.data
        }
      })
    },
    updateDomDetailTable() {
      this.$refs.domDetailTable.getTableData(false)
    },
    // 获取主表点击行参数，用于子表请求参数
    getSubRequestParams(data) {
      this.rowParams.recheckOrderId = data.id
      this.masterDetail.materialTypeNum = data.materialTypeNum
      this.masterDetail.recheckOrderCode = data.recheckOrderCode
      this.masterDetail.vinCode = data.vinCode
      this.masterDetail.modelName = data.modelName
      this.masterDetail.createTime = data.createTime
    },
    getClassName(stutus) {
      let text = ''
      switch (stutus) {
        case '询价中':
          text = 'status-light-blue'
          break
        case '待选择':
          text = 'status-blue'
          break
        case '已预选':
        text = 'status-light-green'
        break
        case '已确认':
          text = 'status-dark-green'
          break
        case '已到货':
          text = 'status-dark-blue'
          break
        case '已领取':
          text = 'status-orange'
          break
        case '已结算':
          text = 'status-gray'
          break
        case '未响应':
          text = 'status-red'
          break
        case '部分到货':
        text = 'status-orange'
        break
        default:
          break
      }
      return text
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.iddss === 1) {
        return 'warning-row'
      } else {
        return 'success-row'
      }
    },
    // 主表顶部按钮操作事件
    handleMasterOperateEvent(data) {
      this.title = data.name
      let self = this
      const fnc = {
        masterDownload: () => {
          const params = { ...this.masterSearchData, ...this.getSearchParams() }
          if (Array.isArray(params.dateRanger)) {
            params.startTime = params.dateRanger[0]
            params.endTime = params.dateRanger[1]
            delete params.dateRanger
          }
          exportExcel(exportAllUrl, params)
        }
      }
      fnc[data.handleName]()
    },
    // 表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name
      const fnc = {
        download: () => {
          console.log(this.rowParams.recheckOrderId)
          exportExcel(exportUrl, {
            recheckOrderId: this.rowParams.recheckOrderId
          })
        }
      }
      fnc[data.handleName]()
    },
    // 子表表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name
      const fnc = {
        detail: () => {
          this.rowDetail(row)
        },
        reinquiry: () => {
          this.$confirm($i18n.t('bomBuyer.prompt2'), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            this.rowReinquiry(row)
          })
        }
      }
      fnc[handleName]()
    },
    disableFields(flag) {
      this.formDescDialog.disabled = flag
      this.formDescDialog.isShowSubmitBtn = !flag
    },
    rowReinquiry(row) {
      let params = {
        id: row.id
      }
      reinquiryRequest(params).then(res => {
        if (res.data.success) {
          this.$message.success(this.$t('common.operateSuccess'))
          // this.subRefresh()
          this.updateDomDetailTable()
        }
      })
    },
    rowDetail(row) {
      this.$refs.detailDrawerRef.drawer = true
      this.$refs.detailDrawerRef.infoData.id = row.id
      this.$refs.detailDrawerRef.supplementForm.remarks = row.remarks
      if(row.materialPhotoUrl) {
        this.$refs.detailDrawerRef.supplementForm.pictureList = (row.materialPhotoUrl?.split(',')).map(ele => {
          return {
            path: ele,
            src: ele
          }
        })
      } else {
        this.$refs.detailDrawerRef.supplementForm.pictureList = []
      }
      
      console.log(this.$refs.detailDrawerRef.supplementForm.pictureList)
      this.$refs.detailDrawerRef.infoData.materialName = row.materialName
      this.$refs.detailDrawerRef.infoData.materialNum = row.materialNum
      this.$refs.detailDrawerRef.infoData.materialCode = row.materialCode
      this.$refs.detailDrawerRef.infoData.deadlineTime = row.deadlineTime
      this.$refs.detailDrawerRef.infoData.demandStatus = row.demandStatus
      this.$refs.detailDrawerRef.infoData.materialPhotoUrl = row.materialPhotoUrl?.split(',') || []
      this.$refs.detailDrawerRef.getTableData()
      this.$refs.detailDrawerRef.getBrandList()
    },
    //图片预览展示
    showImgViewer(row) {
      this.showViewer = true
      this.showViewerImages = row.materialPhotoUrl?.split(',') || []
    },
    //关闭图片预览弹框
    closeViewer() {
      this.showViewer = false
      this.initialIndex = 0
    },
    // 刷新主表
    refresh(isReset = true) {
      this.$nextTick(() => {
        this.$refs.domTable.getTableData(isReset)
      })
    },
    // 刷新子表
    subRefresh(isReset = true) {
      this.$nextTick(() => {
        this.$refs.domDetailTable.getTableData(isReset)
      })
    },
    //清空右侧信息
    subResetData() {
      this.rowParams.recheckOrderId = null
      this.masterDetail.recheckOrderCode = null
      this.masterDetail.vinCode = null
      this.masterDetail.modelName = null
      this.masterDetail.createTime = null
      console.log(this.masterDetail)
      this.$refs.domDetailTable.resetTableData()
    }
  }
}
</script>
<style scoped lang="scss">
.mesProcess {
  /deep/.el-transfer-panel {
    width: 40% !important;
  }
  .warning-row {
    background: oldlace;
  }
}
/deep/ .warning-icon {
  color: #e6a23c;
  padding-left: 4px;
}
/deep/ .status-circle {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 4px;
  margin-right: 4px;
}
/deep/ .status-light-blue {
  background-color: #6a96c8;
}
/deep/ .status-blue {
  background-color: #3c7fcd;
}
/deep/ .status-dark-blue {
  background-color: #2c43c4;
}
/deep/ .status-light-green {
  background-color: #67c23a;
}
/deep/ .status-dark-green {
  background-color: #078159;
}
/deep/ .status-orange {
  background-color: #e6a23c;
}
/deep/ .status-red {
  background-color: #f56c6c;
}
/deep/ .status-gray {
  background-color: #aaaaaa;
}
.content-main {
  display: flex;
  justify-content: space-between;
  .left-table,
  .right-table {
    width: 49%;
  }
  /deep/ .blue-num {
    color: #0066ff;
  }
  .detail-info-main {
    padding-top: 10px;
    .title-p {
      font-size: 18px;
      line-height: 30px;
      margin-bottom: 10px;
    }
    .info-main {
      display: flex;
      flex-wrap: wrap;
      .info-item {
        width: 20%;
        margin-bottom: 10px;
        font-size: 14px;
        .info-label {
          padding-right: 2px;
        }
      }
    }
  }
  .sub-table-table {
    display: inline-block;
    font-size: 14px;
    line-height: 24px;
    padding: 6px 0;
    color: #6399d7;
    border-bottom: 2px solid #6399d7;
    margin-bottom: 20px;
  }
}
</style>
